package net.aydx84318.weather.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;

import net.aydx84318.weather.bean.WeatherAsyncHttpResponseHandler;
import net.aydx84318.weather.bean.WeatherInfo;
import net.aydx84318.weather.bean.WeatherInfo.WeatherData;
import net.aydx84318.weather.bean.WeatherUtils;
import net.mihome.app.R;
import net.mihome.app.utils.PreferenceUtils;

import org.apache.http.Header;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class WeatherActivity extends Activity {
	private WeatherInfo weatherInfo;
	private TextView cityTextView;
	private TextView daTextView;
	private TextView currentWeatherTextView;
	private TextView currentWindTextView;
	private TextView currentTempTextView;
	private TextView index_dTextView;
	private ImageView weather_icon01ImageView;
	private TextView tommow_titleTextView;
	private TextView third_day_titleTextView;
	private ImageView tommow_day_iconImageView;
	private ImageView third_day_iconImageView;
	private TextView tommow_day_weatherTextView;
	private TextView third_day_weahterTextView;
	private TextView tommow_tempTextView;
	private TextView tommow_windTextView;
	private TextView third_day_tempTextView;
	private TextView third_day_windTextView;
    private View weatherSet;
	private View rootView;
	EditText inputServer;
	ImageLoader imageLoader;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		inputServer= new EditText(this);
		setContentView(R.layout.weather_main);
		imageLoader=ImageLoader.getInstance();
		this.weatherInfo=(WeatherInfo) getIntent().getSerializableExtra("weatherInfo");
		cityTextView=(TextView) findViewById(R.id.cityField);
		daTextView=(TextView) findViewById(R.id.date_y);
        weatherSet=findViewById(R.id.weather_setting);
        weatherSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCityInputDialog();
            }
        });
		this.currentWeatherTextView=(TextView) findViewById(R.id.currentWeather);
		this.currentWindTextView=(TextView) findViewById(R.id.currentWind);
		this.currentTempTextView=(TextView) findViewById(R.id.currentTemp);
		this.index_dTextView=(TextView) findViewById(R.id.index_d);
		this.weather_icon01ImageView=(ImageView) findViewById(R.id.weather_icon01);
		this.third_day_titleTextView=(TextView) findViewById(R.id.third_day_title);
		this.tommow_day_iconImageView=(ImageView) findViewById(R.id.tommow_day_icon);
		this.third_day_iconImageView=(ImageView) findViewById(R.id.third_day_icon);
		this.tommow_day_weatherTextView=(TextView) findViewById(R.id.tommow_day_weather);
		this.third_day_weahterTextView=(TextView) findViewById(R.id.third_day_weather);
		
		this.tommow_tempTextView=(TextView) findViewById(R.id.tommow_temp);
		this.tommow_windTextView=(TextView) findViewById(R.id.tommow_wind);
		this.third_day_tempTextView=(TextView) findViewById(R.id.third_day_temp);
		this.third_day_windTextView=(TextView) findViewById(R.id.third_day_wind);
		this.tommow_titleTextView=(TextView) findViewById(R.id.tommow_title);
		this.rootView=findViewById(R.id.rootLayout);
		initViewData();
	}
	public void initViewData(){
		try{
			List<WeatherInfo.Results> results=this.weatherInfo.getResults();
			WeatherInfo.Results result=results.get(0);
			String cityString=result.getCurrentCity();
			if(result.getPm25()!=null&&!"".equals(result.getPm25().trim())){
				cityString=cityString+"(pm2.5 : "+result.getPm25()+")";
			}
			this.cityTextView.setText(cityString);
			//渲染当天天气
			WeatherInfo.Index todayIndex=result.getIndex().get(0);
			WeatherInfo.WeatherData todDataIndex=result.getWeather_data().get(0);
			this.daTextView.setText(todDataIndex.getDate());
			this.currentWeatherTextView.setText(todDataIndex.getWeather());
			this.currentTempTextView.setText(todDataIndex.getTemperature());
			this.currentWindTextView.setText(todDataIndex.getWind());
			this.index_dTextView.setText(todayIndex.getDes());
			//渲染第二天的数据
			WeatherData tommowData=result.getWeather_data().get(1);
			WeatherData thirdDayData=result.getWeather_data().get(2);
			this.tommow_titleTextView.setText(tommowData.getDate());
			this.third_day_titleTextView.setText(thirdDayData.getDate());
			this.tommow_day_weatherTextView.setText(tommowData.getWeather());
			this.third_day_weahterTextView.setText(thirdDayData.getWeather());
			
			this.tommow_tempTextView.setText(tommowData.getTemperature());
			this.tommow_windTextView.setText(tommowData.getWind());
			this.third_day_tempTextView.setText(thirdDayData.getTemperature());
			this.third_day_windTextView.setText(thirdDayData.getWind());
			//根据时间渲染图片
			if(isNight(System.currentTimeMillis())){
				imageLoader.displayImage(todDataIndex.getNightPictureUrl(), this.weather_icon01ImageView);
				imageLoader.displayImage(tommowData.getNightPictureUrl(), this.tommow_day_iconImageView);
				imageLoader.displayImage(thirdDayData.getNightPictureUrl(), this.third_day_iconImageView);
				this.rootView.setBackgroundResource(R.drawable.weather_bg_night);
			}else{
				imageLoader.displayImage(todDataIndex.getDayPictureUrl(), this.weather_icon01ImageView);
				imageLoader.displayImage(tommowData.getDayPictureUrl(), this.tommow_day_iconImageView);
				imageLoader.displayImage(thirdDayData.getDayPictureUrl(), this.third_day_iconImageView);
				this.rootView.setBackgroundResource(R.drawable.weather_bg_day);
			}
		}catch(Exception e){
			showAlertDialog();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(Menu.NONE, Menu.FIRST + 1, 5, "返回").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
		menu.add(Menu.NONE, Menu.FIRST + 2, 5, "设置城市").setIcon(R.drawable.menu_city_manager);
		return super.onCreateOptionsMenu(menu);

	}
	 @Override
	  public void onOptionsMenuClosed(Menu menu) {
	    /**
	     * 每次菜单被关闭时调用. （菜单被关闭有三种情形，menu按钮被再次点击、back按钮被点击或者用户选择了某一个菜单项） TODO
	     * Auto-generated method stub
	     */
	    super.onOptionsMenuClosed(menu);
	  }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getItemId()==Menu.FIRST+1){
			this.finish();
		}else if(item.getItemId()==Menu.FIRST+2){
			showCityInputDialog();
		}
		return true;
	}
	/**
	 * 如果天气信息为空，则展示对话框
	 * */
	public void showAlertDialog(){
		AlertDialog.Builder builder=new AlertDialog.Builder(this);
		builder.setTitle("米宅提示您:");
		builder.setMessage("无法获取到天气信息");
		builder.setNegativeButton("返回",new OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				WeatherActivity.this.finish();
			}
		});
		builder.create().show();
	}
	/**
	 * 弹出输入城市的弹出框
	 * */
	public void showCityInputDialog(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请输入城市").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						arg0.dismiss();
						arg0.cancel();
					}
				});
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
               String text=inputServer.getText().toString();
               PreferenceUtils.setPrefString(WeatherActivity.this,"weather_city", text);
               Toast.makeText(WeatherActivity.this,text,Toast.LENGTH_SHORT).show();
               initWeatherData();
               dialog.dismiss();
               dialog.cancel();
             }
        });
        builder.show();
	}
	public static boolean isNight(long time) {
		SimpleDateFormat df = new SimpleDateFormat("HH");
		String timeStr = df.format(new Date(System.currentTimeMillis()));
		// L.i("liweiping", "timeStr = " + timeStr);
		try {
			int timeHour = Integer.parseInt(timeStr);
			return (timeHour >= 18 || timeHour <= 6);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return false;
	}
    /**
     * 修改地址后刷新天气预报
     * */
	public void initWeatherData(){
        String city=PreferenceUtils.getPrefString(this,"weather_city", "杭州");
        WeatherUtils.getWeather(city, new WeatherAsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int arg0, Header[] arg1, WeatherInfo weatherInfo) {
                // TODO Auto-generated method stub
                WeatherActivity.this.weatherInfo=weatherInfo;
                initViewData();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                // TODO Auto-generated method stub
                Toast.makeText(WeatherActivity.this, "网络异常，无法获取天气预报信息", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
